//
//  BaseChartView.m
//  JiuLe
//
//  Created by 黄鑫 on 16/9/7.
//  Copyright © 2016年 Fine. All rights reserved.
//

#import "BaseChartView.h"

@interface BaseChartView()

@property (strong, nonatomic) UIImageView *imageSlidebar;   //滑杆
@property (strong, nonatomic) UIButton *btnControll;        //控制按钮
@property (strong, nonatomic) UIButton *btnShowNumber;      //显示数据按钮
@property (strong, nonatomic) UIImageView *imageLine;       //滑动虚线
@property (strong, nonatomic) UIImageView *imageSelect;     //阴影图片
@property (strong, nonatomic) UIImageView *imageSelectTwo;  //睡眠中阴影图片
@property (strong, nonatomic) NSMutableArray *arrPoint;     //存储圆点坐标
@property (strong, nonatomic) NSMutableArray *arrPointT;    //存储圆点坐标
@property (strong, nonatomic) NSMutableArray *arrPointTime; //存储圆点坐标对应的时间
@property (assign, nonatomic) int closestPoint;             //最近点

@end

@implementation BaseChartView
@synthesize xAxis     = _xAxis;
@synthesize xAxisMark = _xAxisMark;
@synthesize yAxis     = _yAxis;
@synthesize yAxisMark = _yAxisMark;
@synthesize yAxisSecondary = _yAxisSecondary;
@synthesize chartY;
@synthesize chartX;
@synthesize chartH;
@synthesize chartw;

- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if(self) {
        self.backgroundColor = [UIColor whiteColor];
        viewH                = [UIScreen mainScreen].bounds.size.width ;
        viewW                = [UIScreen mainScreen].bounds.size.width;
        chartH      =        viewH - 210;
        chartw      =        viewW - 40;
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
        viewH                = [UIScreen mainScreen].bounds.size.width ;
        viewW                = [UIScreen mainScreen].bounds.size.width;
        chartH      =        viewH - 210;
        chartw      =        viewW - 40;
    }
    return self;
}

#pragma  mark - drawRect
- (void)drawRect:(CGRect)rect{
    //1.取得图形上下文对象
    CGContextRef context = UIGraphicsGetCurrentContext();
    //抗锯齿
    CGContextSetAllowsAntialiasing(context, true);
    CGContextSetShouldAntialias(context, true);
    CGContextSetStrokeColorWithColor(context, [UIColor grayColor].CGColor);
    //绘制竖线
    //2.创建路径对象
    CGMutablePathRef path = CGPathCreateMutable();
    //绘制横线
    CGPathMoveToPoint(path, nil, chartX, chartY + ((_yAxisMark.count - 1) * self.yInterval));
    CGPathAddLineToPoint(path, nil, chartX + chartw , chartY + ((_yAxisMark.count - 1) * self.yInterval));
    CGContextAddPath(context, path);
    CGContextDrawPath(context, kCGPathFillStroke);
    //3.释放对象
    CGPathRelease(path);
    //绘制X轴标量
    UIFont *font = [UIFont systemFontOfSize:13];//设置字体
    UIColor *color = [UIColor blackColor];//字体颜色
    NSMutableParagraphStyle *style=[[NSMutableParagraphStyle alloc]init];//段落样式
    NSTextAlignment align = NSTextAlignmentLeft;//对齐方式
    style.alignment = align;
    for (int j = 0; j < _xAxisMark.count; j++){
        CGRect rect = CGRectZero;
        if(_baseChartShowDateType == BaseChartShowDateTypeSleeping){//睡眠图表宽比其它表少20
            rect  = CGRectMake((j * self.xInterval) + 10, chartH + chartY, 40, 21);
        }else{
          rect  = CGRectMake((j * self.xInterval), chartH + chartY, 40, 21);
        }
        NSString *text = _xAxisMark[j];
        [text drawInRect:rect withAttributes:@{NSFontAttributeName:font,NSForegroundColorAttributeName:color,NSParagraphStyleAttributeName:style}];
    }
    if(self.baseChartType == BaseChartTypeLineChart){
        [self toDrawLine:context];
        if (self.baseChartShowDateType == BaseChartShowDateTypeSleeping) {
            [self toDrawLineSecondary:context];
        }
    }else{
        [self toDrawRectangle:context];
    }
}

//绘制折线图表
- (void)toDrawLine:(CGContextRef)context{
    //绘制点坐标
    NSMutableArray *arrXAxis = [NSMutableArray array];
    NSMutableArray *arrYAxis = [NSMutableArray array];
    SEL sel = NSSelectorFromString(@"addObject:");
    for (int i = 0; i < self.yAxis.count; i++) {    //显示每日数据是yAxis有24组数据 每组直接存步数
        NSString *str = _yAxis[i];
        if ([str intValue] > -1) {
            CGRect rect = [self getGraphicPositionget:str index:i];
            NSValue *value = [NSValue valueWithCGRect:rect];
            [self toDrawDot:rect color:[UIColor colorWithRed:103/255.0 green:207/255.0 blue:236/255.0 alpha:1.0] context:context];
            [arrXAxis addObject:[NSNumber numberWithFloat:rect.origin.x+ (CircleDiameter/2)]];
            [arrYAxis addObject:[NSNumber numberWithFloat:rect.origin.y+ (CircleDiameter/2)]];
            void (*imp)(id, SEL, id) = (void(*)(id,SEL,id))[self.arrPoint methodForSelector:sel];
            if(imp)
                imp(_arrPoint, sel, value);
            int time = i*5;
            [self.arrPointTime addObject:[NSNumber numberWithInt:time]];
        }
    }
    [self pointLine:context arrXAxis:arrXAxis arrYAxis:arrYAxis type:YES];
    //绘制空心点
    for (int i = 0; i < self.yAxis.count; i++) {
        NSString *str = _yAxis[i];
        if ([str intValue] > -1) {
            CGRect rect = [self getGraphicPositionget:str index:i];
            [self toDrawDot:CGRectMake(CGRectGetMinX(rect) +1, CGRectGetMinY(rect)+1, CGRectGetWidth(rect) -2, CGRectGetHeight(rect)-2) color:[UIColor whiteColor] context:context];
        }
    }
}

//绘制折线图表副线条
- (void)toDrawLineSecondary:(CGContextRef)context{
    //绘制点坐标
    NSMutableArray *arrXAxis = [NSMutableArray array];
    NSMutableArray *arrYAxis = [NSMutableArray array];
    SEL sel = NSSelectorFromString(@"addObject:");
    for (int i = 0; i < self.yAxisSecondary.count; i++) {    //显示每日数据是yAxis有24组数据 每组直接存步数
        NSString *str = _yAxisSecondary[i];
        if ([str intValue] > -1) {
            CGRect rect = [self getGraphicPositionget:str index:i];
            NSValue *value = [NSValue valueWithCGRect:rect];
            [self toDrawDot:rect color:[UIColor colorWithRed:23/255.0 green:143/255.0 blue:255/255.0 alpha:1.0] context:context];
            [arrXAxis addObject:[NSNumber numberWithFloat:rect.origin.x+ (CircleDiameter/2)]];
            [arrYAxis addObject:[NSNumber numberWithFloat:rect.origin.y+ (CircleDiameter/2)]];
            void (*imp)(id, SEL, id) = (void(*)(id,SEL,id))[self.arrPointT methodForSelector:sel];
            if(imp)
                imp(_arrPointT, sel, value);
        }
    }
    [self pointLine:context arrXAxis:arrXAxis arrYAxis:arrYAxis type:NO];
    //绘制空心点
    for (int i = 0; i < self.yAxisSecondary.count; i++) {
        NSString *str = _yAxisSecondary[i];
        if ([str intValue] > -1) {
            CGRect rect = [self getGraphicPositionget:str index:i];
            [self toDrawDot:CGRectMake(CGRectGetMinX(rect) +1, CGRectGetMinY(rect)+1, CGRectGetWidth(rect) -2, CGRectGetHeight(rect)-2) color:[UIColor whiteColor] context:context];
        }
    }
}

//绘制矩形图表
- (void)toDrawRectangle:(CGContextRef)context{
    SEL sel = NSSelectorFromString(@"addObject:");
    for (int i = 0; i < self.yAxis.count; i++) {    //显示每日数据是yAxis有24组数据 每组直接存步数
        NSString *str = _yAxis[i];
        if ([str intValue] > -1) {
            CGRect rect = [self getGraphicPositionget:str index:i];
            NSValue *value = [NSValue valueWithCGRect:rect];
            [self toDrawRect:rect color:[UIColor colorWithRed:103/255.0 green:207/255.0 blue:236/255.0 alpha:1.0] context:context ];
            void (*imp)(id, SEL, id) = (void(*)(id,SEL,id))[self.arrPoint methodForSelector:sel];
            if(imp)
                imp(_arrPoint, sel, value);
        }
    }
}

//获取绘制位置
- (CGRect)getGraphicPositionget:(NSString *)number index:(int)i{
    float yCoordinate ;
    if([number isEqualToString:@"0"]){
        yCoordinate  = chartY + chartH;
    }else{
        yCoordinate  = chartY + chartH - ([number intValue]/_percentage);//5 为单位比例yInterval/每条线代表的单位
    }
    float xCoordinate;
    if(self.baseChartShowDate == BaseChartShowDateDay){
        xCoordinate = chartX + (i * (chartw/288.0));
    }else if (self.baseChartShowDate == BaseChartShowDateWeek){
        xCoordinate = chartX + (i * (chartw/6));
    }else{
        xCoordinate = chartX + (i * (chartw/28));
    }
    CGRect rectS = CGRectZero;
    if(CGRectGetWidth(self.frame) > 320){
        if(_baseChartType == BaseChartTypeLineChart){
            rectS = CGRectMake(xCoordinate - (CircleDiameter/2), yCoordinate - (CircleDiameter/2), CircleDiameter, CircleDiameter);
            return CGRectMake(xCoordinate - (CircleDiameter/2), yCoordinate - (CircleDiameter/2), CircleDiameter, CircleDiameter);
        }else{
            return CGRectMake(xCoordinate - (RectangleWidth/2), yCoordinate - 0.4, RectangleWidth , chartY + chartH - yCoordinate);
        }
    }else{
        if(_baseChartType == BaseChartTypeLineChart){
            return CGRectMake(xCoordinate - (CircleDiameter/2), yCoordinate - CircleDiameter +1, CircleDiameter, CircleDiameter);
        }else{
            return CGRectMake(xCoordinate - (RectangleWidth/2), yCoordinate - (CircleDiameter/2), RectangleWidth, chartY + chartH - yCoordinate);
        }
    }

}

//绘制点
- (void)toDrawDot:(CGRect)dot color:fillColor context:(CGContextRef)context{
    //创建路径并获取句柄
    CGMutablePathRef path = CGPathCreateMutable();
    //将矩形添加到路径中
    CGPathAddEllipseInRect(path,NULL,dot);
    //将路径添加到上下文
    CGContextAddPath(context,path);
    //设置点填充色
    [fillColor setFill];
    //绘制
    CGContextDrawPath(context,kCGPathEOFill);
    CGPathRelease(path);
}

//绘制矩形
- (void)toDrawRect:(CGRect)rectangle color:fillColor context:(CGContextRef)ctx{
    //创建路径并获取句柄
    CGMutablePathRef path = CGPathCreateMutable();
    //将矩形添加到路径中
    CGPathAddRect(path,NULL,rectangle);
    //将路径添加到上下文
    CGContextAddPath(ctx,path);
    //设置矩形填充色
    [fillColor setFill];
    //矩形边框颜色
    [[UIColor whiteColor] setStroke];
    //边框宽度
    CGContextSetLineWidth(ctx,0);
    //绘制
    CGContextDrawPath(ctx,kCGPathFillStroke);
    CGPathRelease(path);
}

//点与点连接
- (void)pointLine:(CGContextRef)context arrXAxis:(NSMutableArray *)arrXAxis arrYAxis:(NSMutableArray *)arrYAxis type:(BOOL)type{
    //CGContextSetAllowsAntialiasing(context,YES);
    CGMutablePathRef pathLine = CGPathCreateMutable();
    for (int j = 0; j < arrYAxis.count - 1; j++) {
        if (type) {
            CGContextSetRGBStrokeColor(context, 103/255.0, 207/255.0, 236/255.0, 1.0);
        }else{
             CGContextSetRGBStrokeColor(context, 23/255.0, 143/255.0, 255/255.0, 1.0);
        }
        CGContextSetLineWidth(context, 1);
        CGContextSetLineJoin(context, kCGLineJoinRound);
        CGPathMoveToPoint(pathLine, nil, [arrXAxis[j] floatValue], [arrYAxis[j] floatValue]);
        CGPathAddLineToPoint(pathLine, nil, [arrXAxis[j+1] floatValue] , [arrYAxis[j+1] floatValue]);
        CGContextAddPath(context, pathLine);
        CGContextDrawPath(context, kCGPathEOFillStroke);
    }
    CGPathRelease(pathLine);
}

#pragma mark - 私有方法
- (void)startDraw{
    [self initChart];
    [_arrPoint removeAllObjects];
    [self setNeedsDisplay];
}

- (void)initChart{
    //图表起点（左上角）
    if(_baseChartShowDateType == BaseChartShowDateTypeSleeping){//睡眠图表宽比其它表少20
        chartX               = 30;
    }else{
        chartX               = 20;
    }
    chartY               = 40;
    self.xInterval       = chartw/(_xAxisMark.count-1);
    self.yInterval       = chartH/(_yAxisMark.count-1);
    if (self.baseChartShowDateType == BaseChartShowDateTypePedometer) {
        CGFloat maxValue = [[_yAxis valueForKeyPath:@"@max.floatValue"] floatValue];
        _percentage = (maxValue/3)/self.yInterval;
    }else if (self.baseChartShowDateType == BaseChartShowDateTypeBreathe){
        _percentage = self.yInterval/10;
    }else if (self.baseChartShowDateType == BaseChartShowDateTypeHeartRate){
        _percentage = self.yInterval/50.0;
    }else if (self.baseChartShowDateType == BaseChartShowDateTypeOxygen){
        _percentage = self.yInterval/10;
    }else if (self.baseChartShowDateType == BaseChartShowDateTypeBodyTemperature){
        _percentage = self.yInterval/10.0;
    }else if (self.baseChartShowDateType == BaseChartShowDateTypeSleeping){
        _percentage = self.yInterval/230.0;
    }
    [self initialization];
}

- (void)initialization{
    //选择状态图片
    if(self.imageSelect == nil){
        self.imageSelect = [[UIImageView alloc] init];
        [self addSubview:self.imageSelect];
    }
    if (_baseChartType == BaseChartTypeLineChart) {
        self.imageSelect.image = [UIImage imageNamed:@"select_dot"];
    }else{
        self.imageSelect.image = [UIImage imageNamed:@"select_histogram"];
    }
    NSInteger index = [self backLastIndex:_yAxis];
    self.imageSelect.frame = [self getGraphicPositionget:_yAxis[index] index:(int)index];
    [self insertSubview:self.imageLine aboveSubview:self.imageSelect];
    
    //深度睡眠选择状态图片
    if (self.baseChartShowDateType == BaseChartShowDateTypeSleeping) {
        if(self.imageSelectTwo == nil){
            self.imageSelectTwo = [[UIImageView alloc] init];
            [self addSubview:self.imageSelectTwo];
        }
        if (_baseChartType == BaseChartTypeLineChart) {
            self.imageSelectTwo.image = [UIImage imageNamed:@"select_dot"];
            self.imageSelectTwo.hidden = NO;
        }else{
            self.imageSelectTwo.image = [UIImage imageNamed:@"select_histogram"];
            self.imageSelectTwo.hidden = YES;
        }
        NSInteger index = [self backLastIndex:_yAxisSecondary];
        self.imageSelectTwo.frame = [self getGraphicPositionget:_yAxisSecondary[index] index:(int)index];
        [self insertSubview:self.imageLine aboveSubview:self.imageSelectTwo];
    }
    
    //显示步数
    if (self.btnShowNumber == nil) {
        self.btnShowNumber = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        self.btnShowNumber.titleLabel.font = [UIFont systemFontOfSize:11.0f];
        [self.btnShowNumber setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        self.btnShowNumber.titleEdgeInsets = UIEdgeInsetsMake(-5, 0, 0, 0);
        [self addSubview:self.btnShowNumber];
    }
    if(self.baseChartShowDateType == BaseChartShowDateTypeSleeping){
        self.btnShowNumber.titleLabel.textAlignment = NSTextAlignmentCenter;
        self.btnShowNumber.titleLabel.font = [UIFont systemFontOfSize:9.0];
        NSInteger index = [self backLastIndex:_yAxis];
        if (self.baseChartType == BaseChartTypeLineChart) {
            self.btnShowNumber.frame = CGRectMake(-14, 0, 70, 32);
            self.btnShowNumber.titleLabel.numberOfLines = 0;
            [self.btnShowNumber setTitle:[NSString stringWithFormat:@"总睡眠%.1f时 \n有效睡眠%.1f时",[_yAxis[index] floatValue]/60.0,[_yAxisSecondary[index] floatValue]/60.0] forState:UIControlStateNormal];
            [self.btnShowNumber setBackgroundImage:[UIImage imageNamed:@"icon_data2"] forState:UIControlStateNormal];
        }else{
            self.btnShowNumber.frame = CGRectMake(-9, 0, 60, 25);
            [self.btnShowNumber setTitle:[NSString stringWithFormat:@"总睡眠%.1f时",[_yAxis[index] floatValue]/60.0] forState:UIControlStateNormal];
            [self.btnShowNumber setBackgroundImage:[UIImage imageNamed:@"icon_data"] forState:UIControlStateNormal];
        }
    }else{
        self.btnShowNumber.frame = CGRectMake(-4, 0, 50, 25);
        NSInteger index = [self backLastIndex:_yAxis];
        [self.btnShowNumber setTitle:[self settingUnit:_yAxis[index]] forState:UIControlStateNormal];
        [self.btnShowNumber setBackgroundImage:[UIImage imageNamed:@"icon_data"] forState:UIControlStateNormal];
    }
    CGPoint center = self.imageSelect.center;
    center.y = self.btnShowNumber.center.y;
    self.btnShowNumber.center = center;
    //滑动按钮
    if (self.btnControll == nil) {
        self.btnControll = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [self.btnControll setBackgroundImage:[UIImage imageNamed:@"icon_slidebutton"] forState:UIControlStateNormal];
        [self.btnControll addTarget:self action:@selector(dragMoving:withEvent:)forControlEvents: UIControlEventTouchDragInside];
        [self.btnControll addTarget:self action:@selector(dragEnded:withEvent:)forControlEvents: UIControlEventTouchUpInside |
         UIControlEventTouchUpOutside];
        [self addSubview:self.btnControll];
    }
    self.btnControll.frame = CGRectMake(0, chartH + SlideButtonHeighe + 20, 40, 40);
    CGPoint center1 = self.imageSelect.center;
    center1.y = self.btnControll.center.y;
    self.btnControll.center = center1;
    //滑竿
    if (self.imageSlidebar == nil) {
        self.imageSlidebar = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon_slidebar"]];
        [self addSubview:self.imageSlidebar];
    }
    self.imageSlidebar.frame = CGRectMake(20, CGRectGetMinY(self.btnControll.frame)+10, chartw+20, 20);
    [self bringSubviewToFront:self.btnControll];

    //虚线
    if (self.imageLine == nil) {
        self.imageLine = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"line"]];
        [self addSubview:self.imageLine];
    }
    self.imageLine.frame = CGRectMake(20, CGRectGetMaxY(self.btnShowNumber.frame), 1, CGRectGetMinY(self.btnControll.frame)-CGRectGetMaxY(self.btnShowNumber.frame));
    CGPoint center2 = self.imageSelect.center;
    center2.y = self.imageLine.center.y;
    self.imageLine.center = center2;

    //返回数据
    if (self.baseChartShowDateType == BaseChartShowDateTypePedometer) {
        if ([self.delegate respondsToSelector:@selector(backData:withTime:)]) {
            NSInteger index = [self backLastIndex:_yAxis];
            if (_baseChartShowDate == BaseChartShowDateWeek) {
                NSMutableArray *arrXAxisMark = [NSString getArrayDatesformat:[NSDate date] type:@"周"];
                arrXAxisMark = (NSMutableArray *)[[arrXAxisMark reverseObjectEnumerator] allObjects];
                [self.delegate backData:_yAxis[index] withTime:arrXAxisMark.lastObject];
            }else if(_baseChartShowDate == BaseChartShowDateAge){
                NSMutableArray *arrXAxisMark = [NSString getArrayDatesformat:[NSDate date] type:@"月"];
                arrXAxisMark = (NSMutableArray *)[[arrXAxisMark reverseObjectEnumerator] allObjects];
                [self.delegate backData:_yAxis[index] withTime:arrXAxisMark.lastObject];
            }else{
                int time = 0;
                for (int i = (int)self.yAxis.count - 1; i > 0; i--) {
                    NSString *str = _yAxis[i];
                    if ([str intValue] > -1) {
                        time = i*5;
                        break;
                    }
                }
                [self.delegate backData:_yAxis[index] withTime:[self backFormatTime:time]];
            }
        }
    }else{
        int index = (int)[self backLastIndex:_yAxis];
        if (_baseChartShowDate == BaseChartShowDateWeek) {
            NSMutableArray *arrXAxisMark = [NSString getArrayDatesformat:[NSDate date] type:@"周"];
            arrXAxisMark = (NSMutableArray *)[[arrXAxisMark reverseObjectEnumerator] allObjects];
            [self.delegate backIndex:index withTime:arrXAxisMark.lastObject];
        }else if(_baseChartShowDate == BaseChartShowDateAge){
            NSMutableArray *arrXAxisMark = [NSString getArrayDatesformat:[NSDate date] type:@"月"];
            arrXAxisMark = (NSMutableArray *)[[arrXAxisMark reverseObjectEnumerator] allObjects];
            [self.delegate backIndex:index withTime:arrXAxisMark.lastObject];
        }else{
            int time = 0;
            for (int i = (int)self.yAxis.count - 1; i > 0; i--) {
                NSString *str = _yAxis[i];
                if ([str intValue] > -1) {
                    time = i*5;
                    break;
                }
            }
            [self.delegate backData:_yAxis[index] withTime:[self backFormatTime:time]];
        }
    }
    
}


- (void)dragMoving:(UIControl *)c withEvent:ev{
    CGPoint point = [[[ev allTouches] anyObject] locationInView:self];
    int xMin ,yMax;
    if (self.baseChartShowDateType == BaseChartShowDateTypeSleeping) {//睡眠图表宽比其它表少20
        xMin = 29; yMax = 30;
    }else{
        xMin = 19; yMax = 20;
    }
    if (point.x > xMin && point.x < (viewW - yMax)) {
        c.center = CGPointMake(point.x, c.center.y);
        self.btnShowNumber.center = CGPointMake(point.x+1, self.btnShowNumber.center.y);
        self.imageLine.center = CGPointMake(point.x, self.imageLine.center.y);
        NSMutableArray *overYAxis = [_yAxis mutableCopy];
        [overYAxis enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj isEqualToString:@"-1"]) {
                [overYAxis removeObject:obj];
            }
        }];
        NSMutableArray *overYAxisSecondary =[_yAxisSecondary mutableCopy];
        [overYAxisSecondary enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj isEqualToString:@"-1"]) {
                [overYAxisSecondary removeObject:obj];
            }
        }];
        for (int i = 0; i < _arrPoint.count; i++){
            float number = [_arrPoint[i] CGRectValue].origin.x;
            if (point.x < number + (CircleDiameter/2) && point.x > number - (CircleDiameter/2)) {
                if (self.baseChartShowDateType == BaseChartShowDateTypeSleeping) {
                    if (_baseChartType == BaseChartTypeLineChart) {
                        [self.btnShowNumber setTitle:[NSString stringWithFormat:@"总睡眠%.1f时 \n有效睡眠%.1f时",[overYAxis[i] floatValue]/60.0,[overYAxisSecondary[i]floatValue]/60.0] forState:UIControlStateNormal];
                        self.imageSelectTwo.frame = [_arrPointT[i] CGRectValue];
                    }else{
                        [self.btnShowNumber setTitle:[NSString stringWithFormat:@"总睡眠%.1f时",[overYAxis[i] floatValue]/60.0] forState:UIControlStateNormal];
                    }
                    self.imageSelect.frame = [_arrPoint[i] CGRectValue];
                }else{
                    [self.btnShowNumber setTitle:[self settingUnit:overYAxis[i]] forState:UIControlStateNormal];
                    self.imageSelect.frame = [_arrPoint[i] CGRectValue];
                }
                self.closestPoint = i;
                break;
            }
        }
    }
}

- (void)dragEnded:(UIControl *)control withEvent:event{
    UIButton *btnDrag = (UIButton *)control;
    NSMutableArray *overYAxis = [_yAxis mutableCopy];
    [overYAxis enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj isEqualToString:@"-1"]) {
            [overYAxis removeObject:obj];
        }
    }];
    NSMutableArray *overYAxisSecondary =[_yAxisSecondary mutableCopy];
    [overYAxisSecondary enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj isEqualToString:@"-1"]) {
            [overYAxisSecondary removeObject:obj];
        }
    }];
    if (self.baseChartShowDateType == BaseChartShowDateTypeSleeping) {
        if (_baseChartType == BaseChartTypeLineChart) {
            [self.btnShowNumber setTitle:[NSString stringWithFormat:@"总睡眠%.1f时 \n有效睡眠%.1f时",[overYAxis[_closestPoint] floatValue]/60,[overYAxisSecondary[_closestPoint] floatValue]/60] forState:UIControlStateNormal];
            self.imageSelectTwo.frame = [_arrPointT[_closestPoint] CGRectValue];
        }else{
            [self.btnShowNumber setTitle:[NSString stringWithFormat:@"总睡眠%.1f时",[overYAxis[_closestPoint] floatValue]/60] forState:UIControlStateNormal];
        }
        self.imageSelect.frame = [_arrPoint[_closestPoint] CGRectValue];
    }else{
        [self.btnShowNumber setTitle:[self settingUnit:overYAxis[_closestPoint]] forState:UIControlStateNormal];
        self.imageSelect.frame = [_arrPoint[_closestPoint] CGRectValue];
    }
    self.btnShowNumber.center = CGPointMake(self.imageSelect.center.x, self.btnShowNumber.center.y);
    self.imageLine.center = CGPointMake(self.imageSelect.center.x, self.imageLine.center.y);
    btnDrag.center = CGPointMake(self.imageSelect.center.x, btnDrag.center.y);
    if (self.baseChartShowDateType == BaseChartShowDateTypePedometer) {
        if ([self.delegate respondsToSelector:@selector(backData:withTime:)]) {
            if (_baseChartShowDate == BaseChartShowDateWeek) {
                NSMutableArray *arrXAxisMark = [NSString getArrayDatesformat:[NSDate date] type:@"周"];
                arrXAxisMark = (NSMutableArray *)[[arrXAxisMark reverseObjectEnumerator] allObjects];
                [self.delegate backData:overYAxis[_closestPoint] withTime:arrXAxisMark[_closestPoint]];
            }else if(_baseChartShowDate == BaseChartShowDateAge){
                NSMutableArray *arrXAxisMark = [NSString getArrayDatesformat:[NSDate date] type:@"月"];
                arrXAxisMark = (NSMutableArray *)[[arrXAxisMark reverseObjectEnumerator] allObjects];
                [self.delegate backData:overYAxis[_closestPoint] withTime:arrXAxisMark[_closestPoint]];
            }else{
                int time = [_arrPointTime[_closestPoint] intValue];
                [self.delegate backData:overYAxis[_closestPoint] withTime:[self backFormatTime:time]];
            }
        }
    }else{
        if (_baseChartShowDate == BaseChartShowDateWeek) {
            NSMutableArray *arrXAxisMark = [NSString getArrayDatesformat:[NSDate date] type:@"周"];
            arrXAxisMark = (NSMutableArray *)[[arrXAxisMark reverseObjectEnumerator] allObjects];
            [self.delegate backIndex:_closestPoint withTime:arrXAxisMark[_closestPoint]];
        }else if(_baseChartShowDate == BaseChartShowDateAge){
            NSMutableArray *arrXAxisMark = [NSString getArrayDatesformat:[NSDate date] type:@"月"];
            arrXAxisMark = (NSMutableArray *)[[arrXAxisMark reverseObjectEnumerator] allObjects];
            [self.delegate backIndex:_closestPoint withTime:arrXAxisMark[_closestPoint]];
        }else if(_baseChartShowDate == BaseChartShowDateDay){
            int time = [_arrPointTime[_closestPoint] intValue];
            [self.delegate backData:overYAxis[_closestPoint] withTime:[self backFormatTime:time]];
        }
    }
}

- (NSString *)backFormatTime:(int )time{
    int hour = time/60;
    int minute = time%60;
    NSString *strTime;
    if (hour < 10) {
        if(minute < 10){
            strTime = [NSString stringWithFormat:@"0%d:0%d",hour,minute];
        }else{
            strTime = [NSString stringWithFormat:@"0%d:%d",hour,minute];
        }
    }else{
        if(minute < 10){
            strTime = [NSString stringWithFormat:@"%d:0%d",hour,minute];
        }else{
            strTime = [NSString stringWithFormat:@"%d:%d",hour,minute];
        }
    }
    return strTime;
}

- (NSInteger)backIndex:(NSMutableArray *)arr{
    NSInteger index = 0;
    for (int i = 0 ; i < arr.count; i++) {
        if ([arr[i] intValue]> -1) {
            index = i;
            break;
        }
    }
    return index;
}

- (NSInteger)backLastIndex:(NSMutableArray *)arr{
    NSInteger index = 0;
    for (int i = (int)arr.count-1 ; i > 0; i--) {
        if ([arr[i] intValue]> -1) {
            index = i;
            break;
        }
    }
    return index;
}

- (NSString *)settingUnit:(NSString *)date{
    if (self.baseChartShowDateType == BaseChartShowDateTypePedometer) {
        return [NSString stringWithFormat:@"%@步",date];

    }else if (self.baseChartShowDateType == BaseChartShowDateTypeHeartRate){
        return [NSString stringWithFormat:@"%@次/分",date];

    }else if (self.baseChartShowDateType == BaseChartShowDateTypeBreathe){
        return [NSString stringWithFormat:@"%@次/分",date];

    }else if (self.baseChartShowDateType == BaseChartShowDateTypeOxygen){
        return [NSString stringWithFormat:@"%@%%",date];

    }else if (self.baseChartShowDateType == BaseChartShowDateTypeBodyTemperature){
        return [NSString stringWithFormat:@"%@℃",date];
    }else{
        return date;
    }
}

#pragma mark - set/get
- (void)setXAxis:(NSMutableArray *)axAxis{
    if (self.xAxis != nil) {
        _xAxis     = [axAxis mutableCopy];
    }
}

- (NSMutableArray *)xAxis{
    if (_xAxis == nil) {
        _xAxis     = [NSMutableArray array];
    }
    return  _xAxis;
}

- (void)setXAxisMark:(NSMutableArray *)xAxisMark{
    if (self.xAxisMark != nil) {
        _xAxisMark = [xAxisMark mutableCopy];
    }
}

- (NSMutableArray *)xAxisMark{
    if (_xAxisMark == nil) {
        _xAxisMark = [NSMutableArray array];
    }
    return _xAxisMark;
}

- (void)setYAxis:(NSMutableArray *)yAxis{
    if (self.yAxis != nil) {
        _yAxis     = [yAxis mutableCopy];
    }
}

- (NSMutableArray *)yAxis{
    if (_yAxis == nil) {
        _yAxis     = [NSMutableArray array];
    }
    return _yAxis;
}

- (void)setYAxisMark:(NSMutableArray *)yAxisMark{
    if (self.yAxisMark != nil) {
        _yAxisMark = [yAxisMark mutableCopy];
    }
}

- (NSMutableArray *)yAxisMark{
    if (_yAxisMark == nil) {
        _yAxisMark = [NSMutableArray array];
    }
    return _yAxisMark;
}

- (NSMutableArray*)yAxisMarkSecondary{
    if (_yAxisSecondary == nil) {
        _yAxisSecondary = [NSMutableArray array];
    }
    return _yAxisSecondary;
}

- (NSMutableArray *)arrPoint{
    if (_arrPoint == nil) {
        _arrPoint = [NSMutableArray array];
    }
    return _arrPoint;
}

- (NSMutableArray *)arrPointT{
    if (_arrPointT == nil) {
        _arrPointT = [NSMutableArray array];
    }
    return _arrPointT;
}

- (NSMutableArray *)arrPointTime{
    if (_arrPointTime == nil) {
        _arrPointTime = [NSMutableArray array];
    }
    return _arrPointTime;
}

@end
